﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ReportPrinting;

namespace BSE.Windows.Test
{
    public partial class PrescriptionForm : BaseForm, IReportMaker
    {
        private DateTimePicker startPicker = null;
        private DateTimePicker endPicker = null;
        private bool initCompleted = false;

        public PrescriptionForm()
        {
            InitializeComponent();
            InitToolStrip();
        }

        private void InitToolStrip()
        {
            sortByPatientToolStripMenuItem.Checked = true;
            toolStripComboBoxType.ComboBox.SelectedIndex = 0;
            startPicker = new DateTimePicker();
            startPicker.Width = 110;
            startPicker.Format = DateTimePickerFormat.Custom;
            startPicker.Value = DateTime.Now.AddMonths(-1);
            startPicker.ValueChanged += new EventHandler(toolStripComboBoxDrug_SelectedIndexChanged);
            ToolStripControlHost host1 = new ToolStripControlHost(startPicker);
            toolStrip1.Items.Insert(8, host1);

            endPicker = new DateTimePicker();
            endPicker.Width = 110;
            endPicker.Format = DateTimePickerFormat.Custom;
            endPicker.ValueChanged += new EventHandler(toolStripComboBoxDrug_SelectedIndexChanged);
            host1 = new ToolStripControlHost(endPicker);
            toolStrip1.Items.Insert(10, host1);
        }

        private void PrescriptionForm_Load(object sender, EventArgs e)
        {
            FillDrugList();
            LoadChufangList();
            initCompleted = true;
        }

        public override void RefreshForm()
        {
            FillDrugList();
            LoadChufangList();
        }

        private void LoadChufangList()
        {
            List<Chufang> chufangList = AnesthesiaBLL.GetAllChufangList(
                toolStripComboBoxDrug.ComboBox.SelectedValue.ToString(),
                startPicker.Value, endPicker.Value, 
                sortByDrugToolStripMenuItem.Checked,
                sortByDoctorToolStripMenuItem.Checked, 
                sortByPatientToolStripMenuItem.Checked);
            LoadChufangList(chufangList);
        }

        private void FillDrugList()
        {
            List<Yaopin> yaopins = AnesthesiaBLL.GetAllYaopin();
            Yaopin p = new Yaopin();
            p.YaopinID = "";
            p.YaopinName = "全部药品";
            yaopins.Insert(0, p);

            toolStripComboBoxDrug.ComboBox.DataSource = yaopins;
            toolStripComboBoxDrug.ComboBox.DisplayMember = "YaopinLongName";
            toolStripComboBoxDrug.ComboBox.ValueMember = "YaopinID";

        }

        private void LoadChufangList(List<Chufang> chufangList)
        {
            listView1.Items.Clear();
            int i = 1;
            foreach (Chufang y in chufangList)
            {
                if ((toolStripComboBoxType.ComboBox.SelectedIndex == 1 && y.IsHospital == 0) ||
                    (toolStripComboBoxType.ComboBox.SelectedIndex == 2 && y.IsHospital == 1))
                    continue;

                ListViewItem lvit = new ListViewItem(i++.ToString());
                lvit.Tag = y;

                if (y.IsHospital == 1)
                    lvit.ImageIndex = 0;
                else
                    lvit.ImageIndex = 1;

                ListViewItem.ListViewSubItem lvsit = new ListViewItem.ListViewSubItem();
                lvsit.Text = y.Lingyao.LingyaoDate.ToShortDateString();
                lvit.SubItems.Add(lvsit);

                lvsit = new ListViewItem.ListViewSubItem();
                lvsit.Text = y.PatientName;
                lvit.SubItems.Add(lvsit);

                lvsit = new ListViewItem.ListViewSubItem();
                lvsit.Text = y.HospitalNo;
                lvit.SubItems.Add(lvsit);

                lvsit = new ListViewItem.ListViewSubItem();
                lvsit.Text = y.Illness;
                lvit.SubItems.Add(lvsit);

                lvsit = new ListViewItem.ListViewSubItem();
                lvsit.Text = y.Lingyao.LingyaoYaopin.YaopinName;
                lvit.SubItems.Add(lvsit);

                lvsit = new ListViewItem.ListViewSubItem();
                lvsit.Text = (-y.Lingyao.LingyaoNumber).ToString();
                lvit.SubItems.Add(lvsit);

                lvsit = new ListViewItem.ListViewSubItem();
                lvsit.Text = y.Doctor.YishiName;
                lvit.SubItems.Add(lvsit);

                lvsit = new ListViewItem.ListViewSubItem();
                lvsit.Text = y.PatientDept.KeshiName;
                lvit.SubItems.Add(lvsit);

                lvsit = new ListViewItem.ListViewSubItem();
                lvsit.Text = y.DoctorDept.KeshiName;
                lvit.SubItems.Add(lvsit);

                lvsit = new ListViewItem.ListViewSubItem();
                lvsit.Text = y.Lingyao.LingyaoCode;
                lvit.SubItems.Add(lvsit);

                listView1.Items.Add(lvit);
            }
        }

        private void toolStripButtonAdd_Click(object sender, EventArgs e)
        {
            ChufangForm form = new ChufangForm();
            form.isHospital = 1;
            if (DialogResult.OK == form.ShowDialog())
            {
                try
                {
                    AnesthesiaBLL.AddChufang(form.chufang);
                    LoadChufangList();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("登记住院处方失败！", "医院", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void toolStripButtonAdd2_Click(object sender, EventArgs e)
        {
            ChufangForm form = new ChufangForm();
            form.isHospital = 0;
            if (DialogResult.OK == form.ShowDialog())
            {
                try
                {
                    AnesthesiaBLL.AddChufang(form.chufang);
                    LoadChufangList();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("登记住院处方失败！", "医院", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void toolStripButtonEdit_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0)
            {
                MessageBox.Show("请先选择处方！", "医院", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            if (listView1.SelectedItems.Count > 1)
            {
                MessageBox.Show("一次只能修改一项处方记录！", "医院", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            Chufang y = listView1.SelectedItems[0].Tag as Chufang;
            ChufangForm form = new ChufangForm();
            form.chufang = y;
            if (DialogResult.OK == form.ShowDialog())
            {
                try
                {
                    AnesthesiaBLL.ModifyChufang(form.chufang);
                    LoadChufangList();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("修改处方失败！", "医院", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void toolStripButtonDel_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0)
            {
                MessageBox.Show("请先选择处方！", "医院", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            if (MessageBox.Show("处方删除后将不能回复。是否确定要删除？", "医院", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                try
                {
                    for (int i = 0; i < listView1.SelectedItems.Count; i++)
                    {
                        Chufang y = listView1.SelectedItems[0].Tag as Chufang;
                        AnesthesiaBLL.DeleteChufang(y);
                    }

                    LoadChufangList();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("删除处方失败！", "医院", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
        }

        private void toolStripComboBoxDrug_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!initCompleted)
                return;

            try
            {
                LoadChufangList();
            }
            catch (Exception ex)
            {
                MessageBox.Show("读取数据失败！", "医院", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void toolStripComboBoxType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!initCompleted)
                return;

            try
            {
                LoadChufangList();
            }
            catch (Exception ex)
            {
                MessageBox.Show("读取数据失败！", "医院", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void sortByDrugToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!initCompleted)
                return;

            try
            {
                LoadChufangList();
            }
            catch (Exception ex)
            {
                MessageBox.Show("读取数据失败！", "医院", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void MakeDocument(ReportDocument reportDocument)
        {
            TextStyle.ResetStyles();

            TextStyle.Normal.Size = 10;
            TextStyle.Heading1.Size = 16;
            TextStyle.Heading1.Bold = false;
            TextStyle.TableHeader.BackgroundBrush = Brushes.White;// Brushes.Blue;
            TextStyle.TableHeader.Brush = Brushes.Black;//Brushes.LightGoldenrodYellow;
            TextStyle.TableHeader.MarginNear = 0.1f;
            TextStyle.TableHeader.MarginFar = 0.1f;
            TextStyle.TableHeader.MarginTop = 0.05f;
            TextStyle.TableHeader.MarginBottom = 0.05f;
            TextStyle.TableRow.MarginNear = 0.1f;
            TextStyle.TableRow.MarginFar = 0.1f;
            TextStyle.TableRow.MarginTop = 0.05f;

            ReportBuilder builder = new ReportBuilder(reportDocument);
            builder.StartLinearLayout(Direction.Vertical);

            Pen innerPen = new Pen(Color.Green, 0.02f);
            builder.AddPageHeader(String.Empty, 
                "麻精药品统计表\n" + 
                startPicker.Value.Year + " 年  " + startPicker.Value.Month + " 月  " + startPicker.Value.Day + " 日 " + "至  " +
                endPicker.Value.Year + " 年  " + endPicker.Value.Month + " 月  " + endPicker.Value.Day + " 日 ", 
                "第 %p 页");
            //builder.AddPageHeader(String.Empty, "" + year + " 年  " + month + "月", String.Empty);

            //builder.AddText("Table with lines using default lines\n");
            // Following line sets up the pen used for lins for tables
            builder.DefaultTablePen = reportDocument.ThinPen;
            List<DataView> dvs = GetDataView();
            for (int i = 0; i < dvs.Count; i++ )
            {
                DataView dv = dvs[i];
                if (i > 0)
                    builder.AddPageBreak();
                builder.AddTable(dv, true);
                builder.CurrentSection.HorizontalAlignment = ReportPrinting.HorizontalAlignment.Center;
                builder.AddColumn("Serial", "序号", 1.0f, true, true);
                builder.AddColumn("PatientName", "患者", 1.8f, true, true);
                builder.AddColumn("HospitalNo", "住院号", 1.8f, true, true);
                builder.AddColumn("Illness", "诊断", 3.6f, true, true);
                builder.AddColumn("YaopinName", "药品", 2.0f, true, true);
                builder.AddColumn("Number", "数量", 1.0f, true, true);
                builder.AddColumn("YishiName", "医师", 1.8f, true, true);
                builder.AddColumn("Code", "处方号", 1.8f, true, true);
                builder.AddColumn("PatientDept", "患者科室", 1.8f, true, true);
                builder.AddColumn("DoctorDept", "医生科室", 1.8f, true, true);
            }
            
            builder.Table.OuterPens = reportDocument.NormalPen;
            builder.FinishLinearLayout();
            reportDocument.SetPageOrientation(1, PageOrientation.Landscape);
        }

        private List<DataView> GetDataView()
        {
            List<DataView> views = new List<DataView>();

            int j = 1;
            DataTable dt = null;
            for (int i = 0; i <  listView1.Items.Count; i++)
            {
                ListViewItem item = listView1.Items[i];
                if (i == 0)
                {
                    j = 1;
                    dt = newDataTable();
                }
                
                Chufang cf = item.Tag as Chufang;
                if (i > 0)
                {
                    Chufang prev = listView1.Items[i - 1].Tag as Chufang;
                    if (cf.PatientDeptName != prev.PatientDeptName)
                    {
                        views.Add(dt.DefaultView);
                        dt = newDataTable();
                    }
                }

                DataRow dr = dt.NewRow();
                dr["Serial"] = j++;
                dr["PatientName"] = cf.PatientName;
                dr["HospitalNo"] = cf.HospitalNo;
                dr["Illness"] = cf.Illness;
                dr["YaopinName"] = cf.Lingyao.LingyaoYaopin.YaopinName;
                dr["Number"] = (-cf.Lingyao.LingyaoNumber).ToString();
                dr["YishiName"] = cf.Doctor.YishiName;
                dr["Code"] = cf.Lingyao.LingyaoCode;
                dr["PatientDept"] = cf.PatientDeptName;
                dr["DoctorDept"] = cf.DoctorDeptName;
                dt.Rows.Add(dr);
            }

            if (dt != null && dt.Rows.Count > 0)
                views.Add(dt.DefaultView);

            return views;
        }

        private DataTable newDataTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Serial");
            dt.Columns.Add("PatientName");
            dt.Columns.Add("HospitalNo");
            dt.Columns.Add("Illness");
            dt.Columns.Add("YaopinName");
            dt.Columns.Add("Number");
            dt.Columns.Add("YishiName");
            dt.Columns.Add("Code");
            dt.Columns.Add("PatientDept");
            dt.Columns.Add("DoctorDept");

            return dt;
        }
    }
}
